package servlet;

import dao.*;
import utils.string.session.SessionStringUtil;
import vo.Fix;
import vo.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.util.HashMap;

public class AddFixServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //在增加到维修中的数目，在设备表中的数据也得修改
        FixDaoImpl fixDao = new FixDaoImpl();
        Fix fix = new Fix();
        //获取数据
        String fix_reason = req.getParameter("fix_reason");
        int fix_num = Integer.parseInt(req.getParameter("fix_num"));
        int equipmentId = Integer.parseInt(req.getParameter("equipmentId"));
        User user = (User) req.getSession().getAttribute(SessionStringUtil.USER);
        //获取现在的时间
        java.util.Date utilDate = new java.util.Date();
        Date date = new Date(utilDate.getTime());
        fix.setFix_date(date);
        fix.setFix_num(fix_num);
        fix.setFix_reason(fix_reason);
        fix.setEquip_id(equipmentId);
        fix.setUser_id(user.getUser_id());
        fixDao.insertFix(fix);
        //进行权限判断和修改
        if(user.getAuth_id() == 1){
            //管理者
            //更改设备里面的数目
            EquipmentDaoImpl equipmentDao = new EquipmentDaoImpl();
            equipmentDao.changeEquipment(equipmentId,fix_num, EquipmentDao.SUBSTRACT_EQUIPMENT_NUM);//因为是借用出去所以原来的数目会下降
        }else{
            //普通用户只需要将using表中的数目进行修改
            UsingDaoImpl usingDao = new UsingDaoImpl();
            int tableUsingId = Integer.parseInt(String.valueOf(req.getSession().getAttribute("tableUsingId")));
            usingDao.substractUsingNum(tableUsingId,fix_num);
        }
             //页面跳转
        jumpToJSP(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       jumpToJSP(req,resp);
    }

    void jumpToJSP (HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //在这里进行判断用户的权限进行不同的JSP页面跳转
        User user = (User) req.getSession().getAttribute(SessionStringUtil.USER);
        TableFixDaoImpl tableFixDao = new TableFixDaoImpl();
        //对应的用户的界面
        HashMap userFixs = tableFixDao.selectByUserId(user.getUser_id());
        HashMap tableFixs = tableFixDao.selectAll();
        req.getSession().setAttribute(SessionStringUtil.ALL_FIXS,tableFixs);
        req.getSession().setAttribute(SessionStringUtil.USER_FIXS,userFixs);
        if(user.getAuth_id() == 1){
            resp.sendRedirect("/equipmentManager_war_explode/manageAllFix.jsp");//跳转到管理者的Fix界面
        }else{
            resp.sendRedirect("/equipmentManager_war_explode/manageUserFix.jsp");//普通用户的界面
        }
    }
}
